package com.smart.community.region.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.smart.community.feign.region.dto.RegionHierarchyInfo;
import com.smart.community.feign.property.service.IPropertyCompanyCommunityFeign;
import com.smart.community.region.entity.Building;
import com.smart.community.region.entity.Community;
import com.smart.community.region.entity.Household;
import com.smart.community.region.entity.Unit;
import com.smart.community.region.mapper.BuildingMapper;
import com.smart.community.region.mapper.CommunityMapper;
import com.smart.community.region.mapper.HouseholdMapper;
import com.smart.community.region.mapper.UnitMapper;
import com.smart.community.region.service.IRegionHierarchyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 区域层级关系服务实现类
 * 
 * 实现房户层级向上追溯的核心服务，为缴费系统提供房户到物业公司的快速定位服务
 * 层级关系：房户(household) → 单元(unit) → 楼栋(building) → 社区(community) → 物业公司
 * 
 * @author Wu.Liang
 * @version 1.0.0
 * @since 2025-01-30
 */
@Slf4j
@Service
public class RegionHierarchyServiceImpl implements IRegionHierarchyService {

    @Autowired
    private HouseholdMapper householdMapper;
    
    @Autowired
    private UnitMapper unitMapper;
    
    @Autowired
    private BuildingMapper buildingMapper;
    
    @Autowired
    private CommunityMapper communityMapper;
    
    @Autowired
    private IPropertyCompanyCommunityFeign propertyCompanyCommunityFeign;

    @Override
    public Long getPropertyCompanyIdByHouseholdId(Long householdId) {
        log.debug("开始查询房户对应的物业公司ID，房户ID: {}", householdId);
        
        if (householdId == null) {
            log.warn("房户ID为空，无法查询物业公司ID");
            return null;
        }
        
        try {
            // 第1步：根据房户ID查询房户信息
            Household household = householdMapper.selectById(householdId);
            if (household == null) {
                log.warn("未找到房户信息，房户ID: {}", householdId);
                return null;
            }
            
            // 直接从房户信息获取社区ID（优化路径，减少查询次数）
            Long communityId = household.getCommunityId();
            if (communityId == null) {
                log.warn("房户信息中社区ID为空，房户ID: {}", householdId);
                return null;
            }
            
            // 第2步：通过Feign接口获取物业公司ID
            Long propertyCompanyId = propertyCompanyCommunityFeign.getPropertyCompanyIdByCommunityId(communityId);
            if (propertyCompanyId == null) {
                log.warn("社区未关联物业公司，社区ID: {}", communityId);
                return null;
            }
            
            log.debug("查询房户对应的物业公司ID成功，房户ID: {}，社区ID: {}，物业公司ID: {}", 
                    householdId, communityId, propertyCompanyId);
            
            return propertyCompanyId;
            
        } catch (Exception e) {
            log.error("查询房户对应的物业公司ID失败，房户ID: {}", householdId, e);
            return null;
        }
    }

    @Override
    public RegionHierarchyInfo getRegionHierarchyByHouseholdId(Long householdId) {
        log.debug("开始查询房户完整层级信息，房户ID: {}", householdId);
        
        if (householdId == null) {
            log.warn("房户ID为空，无法查询层级信息");
            return new RegionHierarchyInfo();
        }
        
        try {
            RegionHierarchyInfo hierarchyInfo = new RegionHierarchyInfo();
            hierarchyInfo.setHouseholdId(householdId);
            
            // 第1步：查询房户信息
            Household household = householdMapper.selectById(householdId);
            if (household == null) {
                log.warn("未找到房户信息，房户ID: {}", householdId);
                return hierarchyInfo;
            }
            
            hierarchyInfo.setHouseholdName(household.getHouseholdCode());
            hierarchyInfo.setCommunityId(household.getCommunityId());
            hierarchyInfo.setBuildingId(household.getBuildingId());
            hierarchyInfo.setUnitId(household.getUnitId());
            
            // 第2步：查询单元信息
            if (household.getUnitId() != null) {
                Unit unit = unitMapper.selectById(household.getUnitId());
                if (unit != null) {
                    hierarchyInfo.setUnitName(unit.getUnitName());
                }
            }
            
            // 第3步：查询楼栋信息
            if (household.getBuildingId() != null) {
                Building building = buildingMapper.selectById(household.getBuildingId());
                if (building != null) {
                    hierarchyInfo.setBuildingName(building.getBuildingName());
                }
            }
            
            // 第4步：查询社区信息，获取物业公司ID
            if (household.getCommunityId() != null) {
                Community community = communityMapper.selectById(household.getCommunityId());
                if (community != null) {
                    hierarchyInfo.setCommunityName(community.getCommunityName());
                    // 通过Feign接口获取物业公司ID
                    Long propertyCompanyId = propertyCompanyCommunityFeign.getPropertyCompanyIdByCommunityId(household.getCommunityId());
                    hierarchyInfo.setPropertyCompanyId(propertyCompanyId);
                    
                    // 注意：这里不查询物业公司名称，因为物业公司信息在物业服务中
                    // 如果需要物业公司名称，应该通过物业服务的Feign接口获取
                }
            }
            
            log.debug("查询房户完整层级信息成功，房户ID: {}，社区ID: {}，物业公司ID: {}", 
                    householdId, hierarchyInfo.getCommunityId(), hierarchyInfo.getPropertyCompanyId());
            
            return hierarchyInfo;
            
        } catch (Exception e) {
            log.error("查询房户完整层级信息失败，房户ID: {}", householdId, e);
            RegionHierarchyInfo errorInfo = new RegionHierarchyInfo();
            errorInfo.setHouseholdId(householdId);
            return errorInfo;
        }
    }

    @Override
    public Map<Long, Long> getPropertyCompanyIdsByHouseholdIds(List<Long> householdIds) {
        log.debug("开始批量查询房户对应的物业公司ID，房户数量: {}", householdIds != null ? householdIds.size() : 0);
        
        if (CollectionUtils.isEmpty(householdIds)) {
            log.warn("房户ID列表为空，无法批量查询物业公司ID");
            return new HashMap<>();
        }
        
        try {
            Map<Long, Long> result = new HashMap<>();
            
            // 批量查询房户信息
            QueryWrapper<Household> householdQuery = new QueryWrapper<>();
            householdQuery.in("id", householdIds)
                          .select("id", "community_id");
            
            List<Household> households = householdMapper.selectList(householdQuery);
            if (CollectionUtils.isEmpty(households)) {
                log.warn("未找到任何房户信息，房户ID列表: {}", householdIds);
                return result;
            }
            
            // 提取所有社区ID
            List<Long> communityIds = households.stream()
                    .map(Household::getCommunityId)
                    .filter(id -> id != null)
                    .distinct()
                    .collect(Collectors.toList());
            
            if (CollectionUtils.isEmpty(communityIds)) {
                log.warn("房户信息中没有有效的社区ID，房户数量: {}", households.size());
                return result;
            }
            
            // 通过Feign接口批量获取物业公司ID
            Map<Long, Long> communityToPropertyMap = new HashMap<>();
            for (Long communityId : communityIds) {
                try {
                    Long propertyCompanyId = propertyCompanyCommunityFeign.getPropertyCompanyIdByCommunityId(communityId);
                    if (propertyCompanyId != null) {
                        communityToPropertyMap.put(communityId, propertyCompanyId);
                    }
                } catch (Exception e) {
                    log.warn("获取社区对应的物业公司ID失败，社区ID: {}", communityId, e);
                }
            }
            
            // 构建最终结果：房户ID到物业公司ID的映射
            for (Household household : households) {
                Long propertyCompanyId = communityToPropertyMap.get(household.getCommunityId());
                if (propertyCompanyId != null) {
                    result.put(household.getId(), propertyCompanyId);
                }
            }
            
            log.debug("批量查询房户对应的物业公司ID成功，请求数量: {}，成功数量: {}", householdIds.size(), result.size());
            
            return result;
            
        } catch (Exception e) {
            log.error("批量查询房户对应的物业公司ID失败，房户ID列表: {}", householdIds, e);
            return new HashMap<>();
        }
    }

    @Override
    public Long getCommunityIdByHouseholdId(Long householdId) {
        log.debug("开始查询房户对应的社区ID，房户ID: {}", householdId);
        
        if (householdId == null) {
            log.warn("房户ID为空，无法查询社区ID");
            return null;
        }
        
        try {
            // 查询房户信息，获取社区ID
            Household household = householdMapper.selectById(householdId);
            if (household == null) {
                log.warn("未找到房户信息，房户ID: {}", householdId);
                return null;
            }
            
            Long communityId = household.getCommunityId();
            log.debug("查询房户对应的社区ID成功，房户ID: {}，社区ID: {}", householdId, communityId);
            
            return communityId;
            
        } catch (Exception e) {
            log.error("查询房户对应的社区ID失败，房户ID: {}", householdId, e);
            return null;
        }
    }

    @Override
    public Map<Long, Long> getCommunityIdsByHouseholdIds(List<Long> householdIds) {
        log.debug("开始批量查询房户对应的社区ID，房户数量: {}", householdIds != null ? householdIds.size() : 0);
        
        if (CollectionUtils.isEmpty(householdIds)) {
            log.warn("房户ID列表为空，无法批量查询社区ID");
            return new HashMap<>();
        }
        
        try {
            Map<Long, Long> result = new HashMap<>();
            
            // 批量查询房户信息
            QueryWrapper<Household> query = new QueryWrapper<>();
            query.in("id", householdIds)
                 .select("id", "community_id");
            
            List<Household> households = householdMapper.selectList(query);
            if (CollectionUtils.isEmpty(households)) {
                log.warn("未找到任何房户信息，房户ID列表: {}", householdIds);
                return result;
            }
            
            // 构建房户ID到社区ID的映射
            for (Household household : households) {
                if (household.getCommunityId() != null) {
                    result.put(household.getId(), household.getCommunityId());
                }
            }
            
            log.debug("批量查询房户对应的社区ID成功，请求数量: {}，成功数量: {}", 
                    householdIds.size(), result.size());
            
            return result;
            
        } catch (Exception e) {
            log.error("批量查询房户对应的社区ID失败，房户ID列表: {}", householdIds, e);
            return new HashMap<>();
        }
    }
}
